package net.sx.minemodule.mvp.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.aroutercomment.UserService;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.crop.TakePhotoHelper;
import com.kedll.library.dialog.ECAlertDialog;
import com.kedll.library.util.BindingUtil;
import com.kedll.library.util.GlideApp;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.ToastUtil;
import com.kedll.library.util.UIUtil;

import net.sx.minemodule.R;
import net.sx.minemodule.databinding.MineActivityAfterSalesRequestBinding;
import net.sx.minemodule.mvp.bean.CheckRequestImg;
import net.sx.minemodule.mvp.bean.OrderSalesReqBean;
import net.sx.minemodule.mvp.presenters.MineOrderAfterSalesReqPresenter;
import net.sx.minemodule.mvp.views.MineOrderAfterSalesReqView;
import net.sx.minemodule.widget.AppPopupWidows;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

import static com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.withCrossFade;

/**
 * 描述:  订单商品 申请售后
 * mOrderProductId (该Activity 需要传入订单中商品项的ID )
 * author:胡邦茂
 * CreateDate: 2019/7/11 9:31
 */
@RuntimePermissions
@Route(path = ARouterPath.PATH_MINE_ORDER_AFTER_SALES_REQUEST)
public class MineOrderAfterSalesRequestActivity extends MyBaseFragmentActivity<MineActivityAfterSalesRequestBinding, MineOrderAfterSalesReqPresenter> implements MineOrderAfterSalesReqView {
    @Autowired(name = ARouterPath.PATH_USER_SERVICE)
    public UserService userService;
    public final static String KEY_ID = "id";
    private int mOrderProductId;
    private OrderSalesReqBean initData;
    //1、退款 2、退款退货
    private int type = 1;
    private String[] whys;
    private ImageAdapter mAdapter;
    private ArrayList<CheckRequestImg> mAdapterData;
    private TakePhotoHelper photoHelper;


    //图片选择adapter
    private class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
        List<CheckRequestImg> list;

        public ImageAdapter(List<CheckRequestImg> list) {
            this.list = list;
        }

        /**
         * 在集合的 最后一个前面添加item
         *
         * @param item
         */
        public void addEndItem(CheckRequestImg item) {
            list.add(list.isEmpty() ? 0 : list.size() - 1, item);
            notifyItemChanged(list.size() - 1);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup vg, int i) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.mine_item_after_sales_img_item, vg, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder vh, int pro) {
            CheckRequestImg item = list.get(pro);
            if (pro == list.size() - 1) {
                //1、最后一张 显示选择
                vh.tv_status.setVisibility(View.GONE);
                vh.iv_remove.setVisibility(View.GONE);
                vh.iv_show.setImageResource(item.getRes());
                vh.iv_show.setOnClickListener(v -> {
                    openPhotoSelect();
                });
            } else {
                //2、显示选择的图片
                vh.iv_remove.setVisibility(View.VISIBLE);
                vh.iv_remove.setOnClickListener(v -> {
                    list.remove(pro);
                    notifyItemRemoved(pro);
                    notifyItemRangeChanged(pro, list.size() - pro);
                });

                GlideApp.with(getContext()).asBitmap()
                        .load(item.getFile())
                        .transition(withCrossFade())
                        .skipMemoryCache(false)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .priority(Priority.HIGH)
                        .centerCrop()
                        .transform(new RoundedCornersTransformation(MyUtils.dp2px(4), 0))
                        .into(vh.iv_show);


                //3、状态操作
                if (item.getStatus() == 0) {
                    vh.tv_status.setVisibility(View.GONE);
                } else {
                    vh.tv_status.setVisibility(View.VISIBLE);
                    vh.tv_status.setTag(item.getStatus());
                    vh.tv_status.setText(item.getStatusMsg());
                    vh.tv_status.setOnClickListener(v -> {
                        if (v.getTag() == null) {
                            return;
                        }
                        //上传失败的状态
                        if (Integer.parseInt(String.valueOf(v.getTag())) == CheckRequestImg.STATUS_ERR) {
                            //点击可重试
                            getPresenter().postImageFile(item);
                        }
                    });
                }
            }


        }

        @Override
        public int getItemCount() {
            return list.size() >= 6 ? 6 : list.size();
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView iv_show;
            ImageView iv_remove;
            TextView tv_status;

            public ViewHolder(View view) {
                super(view);
                iv_show = view.findViewById(R.id.iv_show);
                iv_remove = view.findViewById(R.id.iv_remove);
                tv_status = view.findViewById(R.id.tv_status);
            }
        }
    }

    private View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.tv_type_1) {
                selectType(mBinding.tvType1);
            }

            if (id == R.id.tv_type_2) {
                selectType(mBinding.tvType2);
            }

            if (id == R.id.rl_check) {
                showCheckPopup();
            }


            //提交本次售后申请
            if (id == R.id.tv_submit) {
                HashMap<String, Object> map = new HashMap<>();
                Object easonId = mBinding.tvCheckStatus.getTag();
                if (easonId == null || "0".equals(String.valueOf(easonId))) {
                    ToastUtil.showToast("请选择原因");
                    return;
                }

                String note = mBinding.etOther.getText().toString();
                if (TextUtils.isEmpty(note)) {
                    ToastUtil.showToast("请填写描述");
                    return;
                }


                //图片
                ArrayList<String> imgs = new ArrayList<>();
                for (CheckRequestImg item : mAdapterData) {
                    if (item.getStatus() == CheckRequestImg.STATUS_OK) {
                        imgs.add(item.getUrl());
                    }
                }
                if (imgs.isEmpty()) {
                    ToastUtil.showToast("请上传图片");
                    return;
                }


                //images        上传图片 Json数组
                //note         问题描述(APP)
                //orderItemId   订单详情ID
                //easonId       问题类型(APP)
                //returnType   售后类型 0 退款 1 退款退货 2 换货

                map.put("images", JSON.toJSONString(imgs));
                map.put(" note", note);
                map.put("orderItemId", initData.getId());
                map.put("easonId", easonId);
                map.put("returnType", type);

                getPresenter().submit(map);
            }

        }
    };

    class VH {
        TextView tvTitle;
        View view;
        ImageView ivClose;
        LinearLayout llContent;
        TextView tvSubmit;
    }

    private AppPopupWidows<VH> mClearPopup;

    /**
     * 显示选择售后 原因 popup
     */
    private void showCheckPopup() {
        if (mClearPopup == null) {
            mClearPopup = new AppPopupWidows<>((Activity) getContext(), R.layout.mine_popup_clear_order);
            mClearPopup.setAnimStyle(R.style.timepopwindow_anim_style).setHeight(440);
            mClearPopup.builder(new AppPopupWidows.InitListener<VH>() {
                @Override
                public void onClick(View v) {
                    int id = v.getId();
                    //1、关闭
                    if (id == R.id.iv_clear) {
                        mClearPopup.dismiss();
                        return;
                    }
                    VH vh = mClearPopup.getViewHoder();

                    //2、点击确定
                    if (id == R.id.tv_submit) {
                        if (!vh.tvSubmit.isSelected()) {
                            ToastUtil.showToast("请选择", Gravity.TOP);
                            return;
                        }
                        mClearPopup.dismiss();
                        mBinding.tvCheckStatus.setText(
                                vh.tvSubmit.isSelected()
                                        ?
                                        whys[Integer.parseInt(String.valueOf(vh.tvSubmit.getTag()))]
                                        :
                                        getResources().getString(R.string.str_please_check));
                        mBinding.tvCheckStatus.setTag(vh.tvSubmit.isSelected() ? vh.tvSubmit.getTag() : 0);
                        return;
                    }

                    //3、交互选中
                    checkStatusUI(v);

                }

                private void checkStatusUI(View v) {
                    VH vh = mClearPopup.getViewHoder();
                    for (int i = 0; i < vh.llContent.getChildCount(); i++) {
                        View view = vh.llContent.getChildAt(i);
                        ImageView status = view.findViewById(R.id.iv_status);
                        if (view.getTag() == v.getTag()) {
                            status.setImageResource(status.isSelected() ? R.mipmap.ic_un_checked : R.mipmap.ic_checked);
                            status.setSelected(!status.isSelected());
                            vh.tvSubmit.setSelected(status.isSelected());
                            vh.tvSubmit.setTag(vh.tvSubmit.isSelected() ? view.getTag() : 0);
                        } else {
                            status.setSelected(false);
                            status.setImageResource(R.mipmap.ic_un_checked);
                        }
                    }

                    vh.tvSubmit.setBackgroundResource(
                            vh.tvSubmit.isSelected() ?
                                    R.drawable.shape_round_a541c9_20
                                    : R.drawable.shape_round_color_bbbbbb_20);
                }

                @Override
                public VH bindView(View v) {
                    VH vh = new VH();
                    vh.view = v;
                    vh.ivClose = v.findViewById(R.id.iv_clear);
                    vh.llContent = v.findViewById(R.id.ll_content);
                    vh.tvSubmit = v.findViewById(R.id.tv_submit);
                    vh.tvSubmit.setText(getResources().getString(R.string.picture_confirm));
                    vh.tvTitle = v.findViewById(R.id.tv_hint_title);
                    ((TextView) v.findViewById(R.id.tv_hint_title)).setText("请选择退货原因");

                    vh.ivClose.setOnClickListener(this);
                    vh.tvSubmit.setOnClickListener(this);

                    return vh;
                }

                @Override
                public void initViewData(VH vh, View v) {
                    vh.llContent.removeAllViews();
                    for (int i = 0; i < whys.length; i++) {
                        View view = View.inflate(getContext(), R.layout.mine_popup_clear_order_item, null);
                        TextView name = view.findViewById(R.id.tv_name);
                        String text = whys[i];
                        name.setText(text);
                        vh.llContent.addView(view);
                        view.getLayoutParams().height = UIUtil.dip2px(40);
                        view.setOnClickListener(this);
                        view.setTag(i);

                        if (mBinding.tvCheckStatus.getText().toString().equals(text)) {
                            view.callOnClick();
                        }
                    }
                    vh.tvTitle.setText((type == 1 ? "退款原因" : "退款退货原因"));
                }
            })
                    .setOnDismissListener(() -> {
                        mClearPopup.setBackgroundAlpha(1f);
                    });
        }

        mClearPopup.setBackgroundAlpha(0.5f).show();
    }

    /**
     * 选择类型状态 + 数据
     *
     * @param type
     */
    private void selectType(TextView type) {
        mBinding.tvType1.setBackgroundResource(R.drawable.mine_shape_border_bbb);
        mBinding.tvType1.setTextColor(getResources().getColor(R.color.color_bbbbbb));
        mBinding.tvType2.setBackgroundResource(R.drawable.mine_shape_border_bbb);
        mBinding.tvType2.setTextColor(getResources().getColor(R.color.color_bbbbbb));


        type.setTextColor(getResources().getColor(R.color.color_a541c9));
        type.setBackgroundResource(R.drawable.mine_shape_border_a541c9);
        this.type = (type == mBinding.tvType1 ? 2 : 1);
        whys = getResources().getStringArray(this.type == 2 ? R.array.strs_refund_why_1 : R.array.strs_refund_why_2);
        mBinding.tvCheckHint.setText(this.type == 2 ? R.string.str_refund_return : R.string.str_refund);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        photoHelper = new TakePhotoHelper(this);
        photoHelper.setIsCrop(false);
        photoHelper.setMaxHeight(400);
        photoHelper.setMaxWidth(400);

        mOrderProductId = getIntent().getIntExtra(KEY_ID, -1);
        whys = getResources().getStringArray(R.array.strs_refund_why_1);
        getPresenter().getAfterSalesByOrderId(mOrderProductId);
    }

    private void initView(OrderSalesReqBean res) {
        this.initData = res;
        //1、类型部分
        mBinding.tvType1.setOnClickListener(onClick);
        mBinding.tvType2.setOnClickListener(onClick);
        findViewById(R.id.sv_group).setVisibility(View.VISIBLE);

        //2、商品部分
        BindingUtil.loadImage(mBinding.ivGoodsImgMineOrder, res.getPic(), getContext().getResources().getDrawable(R.drawable.load_error), null);
        mBinding.tvGoodsNameMineOrder.setText(res.getProductName());
        mBinding.tvGoodsNum.setText(String.valueOf("x " + res.getNum()));
        mBinding.tvAttr.setText(getAttrText(res));

        mBinding.tvOrderMoeny.setText(Html.fromHtml("退款金额：<span style='color:red'>￥" + res.getReturnAmount() + "</span>"));
        mBinding.tvOrderIntegral.setText(Html.fromHtml("返回积分 ：<span style='color:red'>" + res.getReturnPoint() + "</span>"));
        mBinding.tvOrderCommi.setText(Html.fromHtml("返还佣金 ：<span style='color:red'>￥" + res.getReturnCommission() + "</span>"));

        //3、选择部分
        mBinding.rlCheck.setOnClickListener(onClick);


        //4、图片部分
        mBinding.rvImg.setLayoutManager(new GridLayoutManager(this, 3));
        mAdapterData = new ArrayList<>();
        mAdapter = new ImageAdapter(mAdapterData);
        mAdapterData.add(new CheckRequestImg(null, R.mipmap.ic_add_img));
        mBinding.rvImg.setAdapter(mAdapter);

        mBinding.tvSubmit.setOnClickListener(onClick);
    }

    /**
     * 获取商品规格 str
     *
     * @param res
     * @return
     */
    private String getAttrText(OrderSalesReqBean res) {
        StringBuilder attrText = new StringBuilder();
        List<OrderSalesReqBean.AttrsBean> attrs = res.getAttrs();
        if (attrs.isEmpty()) {
            return "";
        }
        for (OrderSalesReqBean.AttrsBean item : attrs) {
            attrText.append(item.getName()).append("：").append(item.getValue()).append("\t");
        }
        return attrText.toString();
    }

    @Override
    protected void initEvent() {
        //图片选择回调
        photoHelper.setOnTakePhotoCompleteListener(
                picStr -> Observable.fromIterable(picStr)
                        .compose(bindToLifecycle())
                        .take(1)
                        .subscribe(imgUrl -> {
                            File file = new File(imgUrl);
                            //初始化选择图片
                            initImgSelect(file);
                        }));

    }


    private void initImgSelect(File file) {
        //1、重复选择
        for (CheckRequestImg item : mAdapterData) {
            if (item.getFile() != null && item.getSourceFileAbsPath().equals(file.getAbsolutePath())) {
                ToastUtil.showSnackbar(findViewById(android.R.id.content), "该图片已经存在");
                return;
            }
        }

        CheckRequestImg item = new CheckRequestImg(CheckRequestImg.STATUS_LOADING, file);
        item.setSourceFileAbsPath(file.getAbsolutePath());

        //2、大于1M压缩图片
        if (file.length() / 1024f / 1024f >= 1) {
            File out = new File(getExternalCacheDir() + "/sales_req_" + System.currentTimeMillis() + ".jpg");
            ImageCompress.compressBitmap(file.getAbsolutePath(), 1024, out.getAbsolutePath());
            item.setFile(out);
        }

        mAdapter.addEndItem(item);
        getPresenter().postImageFile(item);
    }


    @Override
    public void dataStatusNotify(CheckRequestImg item) {
        for (int i = 0; i < mAdapterData.size(); i++) {
            CheckRequestImg img = mAdapterData.get(i);
            if (img.getFile() != null && img.getFile().getAbsoluteFile().equals(item.getFile().getAbsoluteFile())) {
                //指定更新
                mAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        ARouter.getInstance().inject(this);
        setTitle("申请售后");
        setTopRightButton("售后须知", v -> {
            String msg = getString(R.string.mine_str_after_hint);
            ECAlertDialog alert = ECAlertDialog.buildAlert(getContext(), msg, "取消", "", null, null);

            alert.getLayoutTitle().setVisibility(View.GONE);
            LinearLayout ll = alert.getLayoutButton();
            ll.removeViewAt(2);
            ll.removeViewAt(1);
            alert.getContentTextView().setGravity(Gravity.LEFT);

            alert.show();
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MineOrderAfterSalesRequestActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void takePhoto() {
        photoHelper.showPopup();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoHelper.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected MineOrderAfterSalesReqPresenter getPresenter() {
        return new MineOrderAfterSalesReqPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.mine_activity_after_sales_request;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void openPhotoSelect() {
        MineOrderAfterSalesRequestActivityPermissionsDispatcher.takePhotoWithPermissionCheck(this);
    }

    @Override
    public void initResult(OrderSalesReqBean res) {
        initView(res);
    }

    private ECAlertDialog hintDialog;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && TextUtils.isEmpty(mBinding.etOther.getText().toString().trim())) {

            hintDialog = ECAlertDialog.buildAlert(getContext()
                    , "退出后编辑内容将不提供保存 ！"
                    , "退出"
                    , "取消"
                    , (dialog, which) -> {
                        finish();
                    }
                    , (dialog, which) -> {
                        hintDialog.dismiss();

                    });

            hintDialog.setTitle(" ");
            hintDialog.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void submitSuccess() {
        hintDialog = ECAlertDialog.buildAlert(getContext()
                , "售后申请已提交成功 ！"
                , ""
                , "知道了"
                , (dialog, which) -> {
                    finish();
                }
                , (dialog, which) -> {
                    finish();
                });

        hintDialog.setTitle(" ");
        hintDialog.show();

    }
}
